<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px" size="large" :model="queryParams" ref="queryFormRef" :inline="true" label-width="98px">
      <el-form-item label="维护项" prop="itemId">
        <el-select filterable @change="handleQuery" clearable class="!w-240px" v-model="queryParams.itemId"
          placeholder="请选择维护项分类">
          <el-option v-for="dict in settingTypeList" :key="dict.id" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备名称" prop="equipmentId">
        <el-input v-model="queryParams.equipmentName" @input="handleQuery" placeholder="请输入设备名称" clearable
          @keyup.enter="handleQuery" class="!w-240px" />
      </el-form-item>
      <el-form-item label="设备编码" prop="equipmentName">
        <el-input v-model="queryParams.code" placeholder="请输入设备编码" clearable @input="handleQuery"
          @keyup.enter="handleQuery" class="!w-240px" />
      </el-form-item>
      <el-form-item label="安装位置" prop="installPosition">
        <el-input v-model="queryParams.installPosition" placeholder="请输入安装位置" clearable @input="handleQuery"
          @keyup.enter="handleQuery" class="!w-240px" />
      </el-form-item>
      <el-form-item label="维护状态" prop="status">
        <el-select @change="handleQuery" v-model="queryParams.status" placeholder="请选择维护状态" clearable class="!w-240px">
          <el-option clearable v-for="dict in getIntDictOptions(DICT_TYPE.KEEP_TYPE)" :key="dict.value"
            :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="计划维护日期" prop="planDate">
        <el-date-picker @change="handleQuery" v-model="queryParams.planDate" value-format="YYYY-MM-DD" type="daterange"
          start-placeholder="开始日期" end-placeholder="结束日期" class="!w-220px" />
      </el-form-item>

      <el-form-item label="责任人" prop="dutyUserName">
        <el-input v-model="queryParams.dutyUserName" placeholder="请输入责任人名称" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
        <el-button type="primary" plain @click="openCreateForm('create')">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button type="primary" plain @click="setWarning()">
          <Icon icon="ep:plus" class="mr-5px" /> 预警设置
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table border row-key="id" v-loading="loading" :data="list" :show-overflow-tooltip="true"
      :cell-style="planDateCellStyle" @selection-change="handleRowCheckboxChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="设备名称" width="120" align="center" prop="equipmentName" />
      <el-table-column label="设备编码" width="120" align="center" prop="equipmentCode" />
      <el-table-column label="安装位置" width="120" align="center" prop="installPosition" />
      <el-table-column label="所属部门" width="120" align="center" prop="deptName" />
      <el-table-column label="维护单号" width="180" align="center" prop="keepNo">
        <template #default="{ row }">
          <el-button type="success" text style="font-size: 14px;" @click="openViewDialog(row.id)">
            {{ row.keepNo }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="维护项" width="150" align="center" prop="itemName" />
      <el-table-column label="维护状态" width="100" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.KEEP_TYPE" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="维护周期(天)" width="120" align="center" prop="cycle" />
      <!-- 计划维护日期 -->
      <el-table-column label="计划维护日期" align="center" width="150" prop="planDate" />

      <!-- 剩余天数 -->
      <el-table-column label="剩余天数" width="100" align="center" prop="remaining" />
      <el-table-column label="责任人" width="100" align="center" prop="dutyUserName" />
      <el-table-column label="创建时间" align="center" prop="createTime" :formatter="dateFormatter" width="180px" />
      <el-table-column label="操作" fixed="right" align="center" min-width="120px">
        <template #default="scope">
          <el-button link type="primary" v-if="scope.row.status == 5" @click="openForm('update', scope.row.id, 10)">
            派工
          </el-button>
          <el-button link type="primary" v-if="scope.row.status == 10" @click="openForm('update', scope.row.id, 5)">
            撤销
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <EquipmnetKeepWaitForm ref="formRef" @success="getList" />

  <!-- 表单弹窗：添加/修改 -->
  <CreateKeepWaitForm ref="createFormRef" @success="getList" />


  <el-drawer v-model="dialogVisible" :with-header="false" size="70%">
    <warningIndex ref="settingRef" v-if="dialogVisible" />
  </el-drawer>

  <waitInfoView ref="viewRef" />

</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { EquipmnetKeepWaitApi, EquipmnetKeepWait } from '@/api/business/equipmnetkeepwait'
import EquipmnetKeepWaitForm from './EquipmnetKeepWaitForm.vue'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { EquipmentKeepSettingTypeApi, EquipmentKeepSettingType } from '@/api/business/equipmentkeepsettingtype'
import warningIndex from '../warningconfig/index.vue'
import waitInfoView from './KeepWaitInfoView.vue'
import CreateKeepWaitForm from './CreateKeepWaitForm.vue'

/** 待维护设备 列表 */
defineOptions({ name: 'EquipmnetKeepWait' })

const planDateCellStyle = ({ row, column, rowIndex, columnIndex }) => {
  if (column.property === 'planDate' || column.property === "remaining") {
    return {
      backgroundColor: row.color || 'transparent',
      textAlign: 'center'
    };
  }
  // 其他列返回默认样式
  return {};
};

// 判断颜色是否为“浅色”背景
const isLightColor = (color) => {
  // 仅处理十六进制格式如 #ffcccc 或 #abc
  let c = color.substring(1) // 去掉 #
  if (c.length === 3) {
    // 扩展 #abc -> #aabbcc
    c = c[0] + c[0] + c[1] + c[1] + c[2] + c[2]
  }
  const rgb = parseInt(c, 16)
  const r = (rgb >> 16) & 0xff
  const g = (rgb >> 8) & 0xff
  const b = (rgb >> 0) & 0xff
  // 使用人眼感知亮度公式
  const luma = 0.2126 * r + 0.7152 * g + 0.0722 * b
  return luma > 128 // 亮度 > 128 认为是浅色
}

//动态设置行样式：背景色 + 自适应文字颜色
// const rowStyle = ({ row }) => {
//   const bgColor = row.color || '#ffffff'
//   const textColor = isLightColor(bgColor) ? '#000000' : '#ffffff' // 浅背景用黑字，深背景用白字

//   return {
//     backgroundColor: bgColor,
//     color: textColor,
//     transition: 'background-color 0.3s, color 0.3s'
//   }
// }

const rowStyle = ({ row }) => {
  const bgColor = row.color || ''
  console.log("??????", bgColor);

  return {
    backgroundColor: bgColor,

  }
}

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<EquipmnetKeepWait[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  keepNo: undefined,
  itemId: undefined,
  equipmentId: undefined,
  status: undefined,
  dutyUserName: undefined,
  equipmentName: undefined,
  excludeStatus: 25,//排除掉已完成的
  code: undefined,
  installPosition: undefined,
  planDate: []
})

const queryParamsSettingType = reactive({
  pageNo: 1,
  pageSize: 100,
  keepNo: undefined,
  itemId: undefined,
  equipmentId: undefined,
  status: undefined,
  dutyUserName: undefined
})


// 可选辅助函数：判断颜色是否为浅色（用于自动切换文字颜色）
// const isLightColor = (color) => {
//   // 简单的亮度计算（适用于十六进制颜色）
//   const c = color.substring(1) // 去掉 #
//   const rgb = parseInt(c, 16)
//   const r = (rgb >> 16) & 0xff
//   const g = (rgb >> 8) & 0xff
//   const b = (rgb >> 0) & 0xff
//   const luma = 0.2126 * r + 0.7152 * g + 0.0722 * b
//   return luma > 128
// }

const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await EquipmnetKeepWaitApi.getEquipmnetKeepWaitPageDamage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

//详细信息
const viewRef = ref()

//详细信息
const openViewDialog = (id) => {
  viewRef.value.openDetailInfo(id)
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number, operation?: number) => {
  formRef.value.open(type, id, operation)
}

/** 新增操作 */
const createFormRef = ref()
const openCreateForm = (type: string, id?: number) => {
  createFormRef.value.open(type, id)
}


const dialogVisible = ref(false) // 弹窗的是否展示

//预警设置
const setWarning = () => {
  dialogVisible.value = true
}


const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: EquipmnetKeepWait[]) => {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await EquipmnetKeepWaitApi.exportEquipmnetKeepWaitDamage(queryParams)
    download.excel(data, '待维护设备.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

//所有维护项
const settingTypeList = ref([])

const getSettingTypeList = async () => {
  const data = await EquipmentKeepSettingTypeApi.getEquipmentKeepSettingTypePageDamage(queryParamsSettingType);
  settingTypeList.value = data.list

}

// 获取今天的日期
const today = new Date()

/** 初始化 **/
onMounted(() => {
  getList()
  getSettingTypeList()
})



</script>
